<template>
  <vab-dialog v-model="dialogFormVisible" append-to-body title="权限设置" width="500px" @close="close">
    <el-form ref="formRef" label-width="80px">
      <el-tree
        ref="treeRef"
        :data="menuData"
        :default-checked-keys="form.permission"
        :default-expand-all="true"
        node-key="menuId"
        :props="defaultProps"
        show-checkbox
        @check="handleCheckChange"
      />
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </template>
  </vab-dialog>
</template>
<script setup lang="ts">
import { getMenuList, doRolePermission as doEdit } from '/@/api/sys.ts'

defineOptions({
  name: 'PermissionEdit',
})
const emit = defineEmits(['fetch-data'])
const $baseMessage = inject<any>('$baseMessage')
const formRef = ref<any>(null)
const treeRef = ref<any>(null)
const title = ref<string>('')
const dialogFormVisible = ref<boolean>(false)
const menuData = ref<any>([])
const form = reactive<any>({
  roleId: '',
  permission: [],
})
const defaultProps = {
  children: 'children',
  label: 'name',
}
const showEdit = (row: any) => {
  dialogFormVisible.value = true
  nextTick(() => {
    if (!row) title.value = '添加'
    else {
      form.roleId = row.roleId
      form.permission = row.permissions ? row.permissions.split(',').map(Number) : []
    }
  })
}

defineExpose({
  showEdit,
})

const close = () => {
  emit('fetch-data')
  dialogFormVisible.value = false
}

const save = async () => {
  const { message }: any = await doEdit(form)
  $baseMessage(message, 'success', 'hey')
  close()
}

const fetchMenuData = async () => {
  const { data } = await getMenuList()
  menuData.value = data
}

const handleCheckChange = (_: any, data: any) => {
  form.permission = data.checkedKeys
}

onBeforeMount(() => {
  fetchMenuData()
})
</script>
<style scoped lang="scss"></style>
